package org.mixed;

import org.antlr.v4.runtime.CharStream;
import org.antlr.v4.runtime.CharStreams;
import org.antlr.v4.runtime.CommonTokenStream;
import org.mixed.antlr4.MixScriptLexer;
import org.mixed.antlr4.MixScriptParser;
import org.mixed.script.MixScriptVisitor;
import org.mixed.script.runtime.MixScriptClassLoader;

import java.io.FileOutputStream;
import java.io.IOException;

public class Main {
    public static void main(String[] args) throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException {
        String sql= "println('hello world!');";
        CharStream input = CharStreams.fromString(sql);  //将输入转成antlr的input流
        MixScriptLexer lexer = new MixScriptLexer(input);  //词法分析
        CommonTokenStream tokens = new CommonTokenStream(lexer);  //转成token流
        MixScriptParser parser = new MixScriptParser(tokens); // 语法分析
        MixScriptParser.ProgramContext tree = parser.program();  //获取某一个规则树，这里获取的是最外层的规则，也可以通过sql()获取sql规则树......
        System.out.println(tree.toStringTree(parser)); //打印规则数
        MixScriptVisitor visitor = new MixScriptVisitor().visit(tree);
        byte[] bytecode = visitor.bytecode();
        new FileOutputStream("scripts/HelloWorld.class").write(bytecode);
        Class<?> aClass = new MixScriptClassLoader(bytecode).loadClass("HelloWorld");
        Object o = aClass.newInstance();
        System.out.println(o);
    }
}
